<template>
  <div>
    <FixedOperation>
      <div class="flex items-center justify-between">
        <div class="leading-30px">
          <div class="inline-block">
            <svg-icon
              :icon-class="'svg_purchaseorder'"
              class="w-30px h-30px align-middle"
            />
            <span
              class="text-#000 leading-30px ml-10px text-16px font-bold align-bottom"
              >采购订单审批</span
            >
          </div>
          <div
            class="inline-block text-15px ml-10px"
            style="vertical-align: bottom"
            v-if="bpmnStatus"
          >
            <i
              :class="
                bpmnStatus == '审批通过'
                  ? 'h-8px w-8px bg-#fe9400 inline-block rounded'
                  : bpmnStatus == '流程未发起'
                  ? 'h-8px w-8px bg-#ccc inline-block rounded'
                  : 'h-8px w-8px bg-#10d070 inline-block rounded'
              "
            ></i>
            {{ bpmnStatus }}
          </div>
        </div>
        <div class="text-right">
          <slot></slot>
          <el-button
            type="primary"
            plain
            @click="handleSubmit('examine')"
            v-if="isExamine && isCanStart"
            >发起申请</el-button
          >
          <el-button
            type="primary"
            @click="handleSubmit('save')"
            v-if="!formDisabled"
            >保存</el-button
          >
          <!-- <el-button @click="handleReset(form)" v-if="isCanStart"
            >重置</el-button
          > -->
          <el-button type="primary" plain @click="handleReturn">返回</el-button>
        </div>
      </div>
    </FixedOperation>
    <div class="app-container form-box">
      <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        :disabled="formDisabled"
        label-width="150px"
      >
        <el-collapse v-model="activeNames">
          <!-- 基本信息 -->
          <el-collapse-item name="基本信息" disabled>
            <template #title>
              <TitleName
                title="基本信息"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName
              ><!-- px-30  -->
            </template>
            <el-row :gutter="80">
              <el-col :span="12">
                <el-form-item label="订单标题" prop="title">
                  <el-input
                    v-model="formData.title"
                    :disabled="
                      fieldDisabled.indexOf('订单标题') == -1 ? false : true
                    "
                    placeholder="请输入订单标题"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.number">
                <el-form-item label="订单编号" prop="number">
                  <el-input
                    disabled
                    v-model="formData.number"
                    placeholder="请输入订单编号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="7" style="padding-right: 0px">
                <el-form-item label="产品属性" prop="proProperty">
                  <el-select
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('产品属性') == -1 ? false : true
                    "
                    v-model="formData.proProperty"
                    placeholder="请选择产品属性"
                  >
                    <el-option
                      v-for="item in product_property"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5" style="padding-left: 0px">
                <el-form-item label="产品类型" prop="proType" label-width="0">
                  <template #label="{ label }">
                    <div class="hidden">{{ label }}</div>
                  </template>
                  <el-select
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('产品属性') == -1 ? false : true
                    "
                    v-model="formData.proType"
                    placeholder="请选择产品类型"
                  >
                    <el-option
                      v-for="item in order_pro_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="属性" prop="property">
                  <el-radio-group
                    v-model="formData.property"
                    :disabled="
                      fieldDisabled.indexOf('属性') == -1 ? false : true
                    "
                  >
                    <el-radio
                      v-for="item in order_property"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属业务分类" prop="businessType">
                  <el-tree-select
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('所属业务分类') == -1 ? false : true
                    "
                    v-model="formData.businessType"
                    placeholder="请选择业务分类"
                    :data="businessTypeOption"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="fieldHidden.indexOf('订单金额') == -1">
                <el-form-item label="订单金额" prop="price">
                  <el-input
                    v-model="formData.price"
                    :disabled="
                      fieldDisabled.indexOf('订单金额') == -1 ? false : true
                    "
                    placeholder="请填写订单金额"
                    ><template v-slot:append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="建议供应商名称" prop="customerId">
                  <el-select
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('建议供应商名称') == -1
                        ? false
                        : true
                    "
                    v-model="formData.customerId"
                    placeholder="请选择供应商名称"
                    @focus="selectCustomerFn('customerId')"
                  >
                    <el-option
                      v-for="item in customerOption['customerId']"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col> -->
              <!-- <el-col :span="12">
                <el-form-item label="建议供应商联系人" prop="cusLinkId">
                  <el-select
                    v-model="formData.cusLinkId"
                    placeholder="请选择联系人，跟供应商联动"
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('建议供应商联系人') == -1
                        ? false
                        : true
                    "
                    clearable
                    @change="changeLinkName"
                    :loading="loadingSelect"
                    no-data-text="未查询到联系人"
                  >
                    <el-option
                      v-for="item in contactsOptions"
                      :key="item.id"
                      :label="item.contactName"
                      :value="item.id"
                    >
                      <div>
                        <span>{{ item.contactName }}</span>
                        <span v-if="item.contactNumber"
                          >({{ item.contactNumber }})</span
                        >
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col> -->
              <!-- <el-col :span="12">
                <el-form-item label="建议供应商编码" prop="customerNumber">
                  <el-input
                    :disabled="true"
                    v-model="formData.customerNumber"
                    placeholder="根据“供应商”的选择自动带出"
                  />
                </el-form-item>
              </el-col> -->
              <!-- <el-col :span="12">
                <el-form-item label="建议供应商联系方式" prop="linkPhone">
                  <el-input
                    :disabled="
                      fieldDisabled.indexOf('建议供应商联系方式') == -1
                        ? false
                        : true
                    "
                    v-model="formData.linkPhone"
                    placeholder="填写联系人手机、电话、邮箱"
                  />
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="合同名称" prop="contractName">
                  <el-input
                    @click="activeDialog"
                    placeholder="请选择关联合同"
                    v-model="formData.contractName"
                    clearable
                    @clear="clearAll"
                  ></el-input>
                  <!-- <el-select
                    v-model="formData.contractId"
                    placeholder="请输入合同名称检索合同"
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('合同名称') == -1 ? false : true
                    "
                    suffix-icon="Search"
                    remote-show-suffix
                    :suffix-transition="false"
                    filterable
                    remote
                    clearable
                    :remote-method="queryContract"
                    @change="changeContract"
                    :loading="loadingSelect"
                    no-data-text="未查询到合同"
                  >
                    <el-option
                      v-for="item in contractOptions"
                      :key="item.rcId"
                      :label="item.contractName"
                      :value="item.rcId"
                    >
                      <div>
                        <span>{{ item.contractName }}</span>
                      </div>
                    </el-option>
                  </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="关联项目" prop="projectId">
                  <el-input
                    @click="selectPro"
                    placeholder="请选择关联项目"
                    v-model="formData.projectName"
                    clearable
                    :suffix-icon="'el-icon-search'"
                    @clear="clearPro"
                  ></el-input>
                  <!-- <el-select
                    v-model="formData.projectId"
                    placeholder="请输入项目名称检索项目"
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('关联项目') == -1 ? false : true
                    "
                    suffix-icon="Search"
                    remote-show-suffix
                    :suffix-transition="false"
                    filterable
                    remote
                    :remote-method="queryProject"
                    @change="changeProject"
                    :loading="loadingSelect"
                    no-data-text="未查询到项目"
                  >
                    <el-option
                      v-for="item in projectOptions"
                      :key="item.projectId"
                      :label="item.proName"
                      :value="item.projectId"
                    >
                      <div>
                        <span>{{ item.proName }}</span>
                      </div>
                    </el-option>
                  </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同编号" prop="contractNumber">
                  <el-input
                    disabled
                    v-model="formData.contractNumber"
                    placeholder="请输入合同编号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目编码" prop="projectNumber">
                  <el-input
                    disabled
                    v-model="formData.projectNumber"
                    placeholder="请输入项目编码"
                  />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="业务部门" prop="transactionDept">
                  <el-tree-select
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('业务部门') == -1 ? false : true
                    "
                    v-model="formData.transactionDept"
                    placeholder="请选择业务部门"
                    :data="departmentOption"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children'
                    }"
                  />
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="发票类型" prop="invoiceType">
                  <el-select
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('发票类型') == -1 ? false : true
                    "
                    v-model="formData.invoiceType"
                    placeholder="请选择发票类型"
                  >
                    <el-option
                      v-for="item in invoice_manage_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="业务员" prop="_transactionId">
                  <el-select
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('业务员') == -1 ? false : true
                    "
                    v-model="formData._transactionId"
                    placeholder="请选择业务员"
                    @focus="selectUserFn('transactionId')"
                  >
                    <el-option
                      v-for="item in userOption['transactionId']"
                      :key="item.uuid"
                      :label="item.label"
                      :value="item.uuid"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col> -->
              <!-- <el-col :span="12">
                <el-form-item label="仓库" prop="warehouse">
                  <el-select
                    v-model="formData.warehouse"
                    placeholder="请输入仓库名称检索仓库"
                    class="w-full"
                    filterable
                    remote
                    :remote-method="val => queryWhsLimitEnt(val)"
                    :loading="loadingSelect"
                    no-data-text="未查询到仓库"
                    >
                    <el-option
                      v-for="item in whsOptLimitEnt"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="交货日期" prop="deliveryDate">
                  <el-date-picker
                    style="width: 100%"
                    v-model="formData.deliveryDate"
                    type="date"
                    :disabled="
                      fieldDisabled.indexOf('交货日期') == -1 ? false : true
                    "
                    placeholder="交货日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="运输方式" prop="transportType">
                  <el-select
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('运输方式') == -1 ? false : true
                    "
                    v-model="formData.transportType"
                    placeholder="请选择运输方式"
                  >
                    <el-option
                      v-for="item in order_transport_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="交货地点" prop="transportPlace">
                  <el-input
                    v-model="formData.transportPlace"
                    :disabled="
                      fieldDisabled.indexOf('交货地点') == -1 ? false : true
                    "
                    placeholder="请输入交货地点"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="运费承担" prop="transportMan">
                  <el-select
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('运费承担') == -1 ? false : true
                    "
                    v-model="formData.transportMan"
                    placeholder="请选择运费承担"
                  >
                    <el-option
                      v-for="item in order_transport_man"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.createTime">
                <el-form-item label="申请日期" prop="createTime">
                  <el-date-picker
                    disabled
                    style="width: 100%"
                    v-model="formData.createTime"
                    type="date"
                    placeholder="申请日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属公司 " prop="deptId">
                  <el-tree-select
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('所属公司') == -1 ? false : true
                    "
                    v-model="formData.deptId"
                    placeholder="请选择所属公司"
                    default-expand-all
                    :data="companyOption"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children'
                    }"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.createName">
                <el-form-item label=" 申请人" prop="createName">
                  <el-input
                    disabled
                    v-model="formData.createName"
                    placeholder="系统自动带入新建的用户名称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.createDept">
                <el-form-item label="申请部门" prop="createDept">
                  <el-tree-select
                    class="w-full"
                    disabled
                    v-model="formData.createDept"
                    placeholder="系统自动带入申请部门"
                    :data="departmentOption"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children'
                    }"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 采购明细 -->
          <el-collapse-item name="采购明细" disabled>
            <template #title>
              <TitleName
                title="采购明细"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <avue-crud
              ref="crudProduct"
              :disabled="
                !formDisabled
                  ? fieldDisabled.indexOf('采购明细') == -1
                    ? false
                    : true
                  : true
              "
              :option="crudOptionProduct"
              :data="formData.productInfoList"
              class="hide-required-asterisk"
            >
              <template #menu-left
                ><el-button
                  type="primary"
                  icon="Plus"
                  :disabled="
                    !formDisabled
                      ? fieldDisabled.indexOf('采购明细') == -1
                        ? false
                        : true
                      : true
                  "
                  class="w-full"
                  @click="addProduct"
                  >添加产品</el-button
                ></template
              >
              <template #warehouse-header="{ column }">
                <span class="text-red pr-2">*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #customerId-header="{ column }">
                <span
                  class="text-red pr-2"
                  v-if="fieldHidden.indexOf('采购单价') == -1"
                  >*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #num-header="{ column }">
                <span class="text-red pr-2">*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #price-header="{ column }">
                <span class="text-red pr-2">*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #valorem-header="{ column }">
                <span class="text-red pr-2">*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #warehouse-form="{ row }">
                <el-select
                  v-model="row.warehouse"
                  placeholder="请输入仓库名称检索仓库"
                  class="w-full"
                  :disabled="
                    !formDisabled
                      ? fieldDisabled.indexOf('采购明细') == -1
                        ? false
                        : true
                      : true
                  "
                  suffix-icon="Search"
                  remote-show-suffix
                  :suffix-transition="false"
                  filterable
                  remote
                  @change="val => changeWhs(val, row)"
                  :remote-method="
                    val => queryWhsLimitEnt(val, { unit: formData.deptId })
                  "
                  :loading="loadingSelect"
                  no-data-text="未查询到仓库"
                >
                  <el-option
                    v-for="item in whsOptLimitEnt"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </template>
              <template #customerId-form="{ row }">
                <el-select
                  class="w-full"
                  v-model="row.customerId"
                  placeholder="请选择供应商"
                  @focus="selectCustomerFn('customerId', row)"
                >
                  <el-option
                    v-for="item in supplierOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  ></el-option>
                </el-select>
                <!-- <el-select
                  v-model="row.customerId"
                  placeholder="请选择供应商名称"
                  class="w-full"
                  :disabled="
                    !formDisabled
                      ? fieldDisabled.indexOf('采购明细') == -1
                        ? false
                        : true
                      : true
                  "
                  suffix-icon="Search"
                  remote-show-suffix
                  :suffix-transition="false"
                  filterable
                  remote
                  @change="val => changeSupplier(val, row)"
                  :remote-method="val => querySupplier(val)"
                  :loading="loadingSelect"
                  no-data-text="未查询到仓库"
                >
                  <el-option
                    v-for="item in supplierOptions"
                    :key="item.id"
                    :label="item.supplierName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select> -->
              </template>
              <template #menu="{ row, index }">
                <el-button
                  plain
                  icon="Delete"
                  link
                  :disabled="
                    !formDisabled
                      ? fieldDisabled.indexOf('采购明细') == -1
                        ? false
                        : true
                      : true
                  "
                  @click="delRowProduct(row, index)"
                  >删除</el-button
                >
              </template>
              <template #empty>
                <div>暂无数据</div>
              </template>
              <template
                #footer
                v-if="fieldHidden.indexOf('采购单价') == -1 ? true : false"
              >
                <el-row
                  class="bg-#f8f8f9 border-solid border-1 border-#ebeef5 pr-5"
                >
                  <el-col :span="24" class="py-2 text-right">
                    产品记录数：<span class="text-blue-500"
                      >{{ countCrudData.num }}条</span
                    >
                    产品总数：<span class="text-blue-500">{{
                      countCrudData.total
                    }}</span
                    >个 产品总售价：<span class="text-blue-500"
                      >{{ countCrudData.totalDiscountPrice }}元</span
                    >
                    <!-- 整单税率：<span class="text-blue-500"
                    >{{ countCrudData.taxRate }}%</span
                  > -->
                    产品采购总价：
                    <span class="text-blue-500"
                      >{{ countCrudData.totalPrice }}元</span
                    >
                  </el-col></el-row
                >
                <!-- <el-button
                  plain
                  type="primary"
                  icon="Plus"
                  :disabled="fieldDisabled.indexOf('采购明细') == -1 ? false : true"
                  class="w-full"
                  @click="addProduct"
                  >添加产品</el-button
                > -->
              </template>
            </avue-crud>
          </el-collapse-item>
          <!-- 付款计划 -->
          <el-collapse-item
            name="付款计划"
            disabled
            v-if="fieldHidden.indexOf('付款计划') == -1"
          >
            <template #title>
              <TitleName
                title="付款计划"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <el-row>
              <el-col :span="24">
                <avue-crud
                  ref="crudRepayment"
                  :disabled="
                    !formDisabled
                      ? fieldDisabled.indexOf('付款计划') == -1
                        ? false
                        : true
                      : true
                  "
                  :option="crudOptionRepayment"
                  :data="formData.payPlanList"
                  class="hide-required-asterisk"
                >
                  <template #menu-left
                    ><el-button
                      type="primary"
                      icon="Plus"
                      :disabled="
                        !formDisabled
                          ? fieldDisabled.indexOf('付款计划') == -1
                            ? false
                            : true
                          : true
                      "
                      class="w-full"
                      @click="addRowRepayment"
                      >添加期次</el-button
                    ></template
                  >
                  <!-- <template #payPlanDate-header="{ column }">
                    <span class="text-red pr-2">*</span
                    ><span>{{ column.label }}</span>
                  </template>
                  <template #proportion-header="{ column }">
                    <span class="text-red pr-2">*</span
                    ><span>{{ column.label }}</span>
                  </template>
                  <template #price-header="{ column }">
                    <span class="text-red pr-2">*</span
                    ><span>{{ column.label }}</span>
                  </template>
                  <template #payType-header="{ column }">
                    <span class="text-red pr-2">*</span
                    ><span>{{ column.label }}</span>
                  </template>
                  <template #settleType-header="{ column }">
                    <span class="text-red pr-2">*</span
                    ><span>{{ column.label }}</span>
                  </template> -->
                  <template #period="{ row }">
                    <span>{{ rowIndex(row) }}</span>
                  </template>
                  <template #bankCard-form="{ row }">
                    <el-select
                      class="w-full"
                      v-model="row.bankCard"
                      :disabled="
                        !formDisabled
                          ? fieldDisabled.indexOf('付款计划') == -1
                            ? false
                            : true
                          : true
                      "
                      placeholder="请选择收款账号"
                    >
                      <el-option
                        v-for="item in order_bank_card"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                        <div class="flex justify-between">
                          <span>{{ item.label }}</span
                          ><span>{{ item.value }}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </template>
                  <template #menu="{ row, index }">
                    <el-button
                      plain
                      icon="Delete"
                      link
                      :disabled="
                        !formDisabled
                          ? fieldDisabled.indexOf('付款计划') == -1
                            ? false
                            : true
                          : true
                      "
                      @click="delRowRepayment(row, index)"
                      >删除</el-button
                    >
                  </template>
                  <template #empty>
                    <div>暂无数据</div>
                  </template>
                  <template #footer>
                    <el-row
                      class="bg-#f8f8f9 border-solid border-1 border-#ebeef5 pr-5"
                    >
                      <el-col :span="24" class="py-2 text-right">
                        总计划期次： {{ repaymentStatisticsData.num }}期
                        总付款占比：{{ repaymentStatisticsData.proportion }}%
                        总付款金额：¥
                        {{ repaymentStatisticsData.totalPrice }}
                      </el-col></el-row
                    >
                    <!-- <el-button
                      plain
                      type="primary"
                      icon="Plus"
                      :disabled="
                        fieldDisabled.indexOf('付款计划') == -1 ? false : true
                      "
                      class="w-full"
                      @click="addRowRepayment"
                      >添加期次</el-button
                    > -->
                  </template>
                </avue-crud>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 其他信息 -->
          <el-collapse-item name="其他信息" disabled>
            <template #title>
              <TitleName
                title="其他信息"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <el-row :gutter="80">
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-select
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('状态') == -1 ? false : true
                    "
                    v-model="formData.status"
                    placeholder="请选择状态"
                  >
                    <el-option
                      v-for="item in order_status"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="终止原因" prop="stopReason">
                  <el-input
                    :disabled="
                      fieldDisabled.indexOf('终止原因') == -1 ? false : true
                    "
                    v-model="formData.stopReason"
                    placeholder="填写终止原因"
                  />
                </el-form-item>
              </el-col>
              <el-col
                :span="formData.isInternationalOperate == '1' ? 6 : 12"
                style="padding-right: 0px"
              >
                <el-form-item
                  label="是否国际化经营"
                  prop="isInternationalOperate"
                >
                  <el-radio-group
                    v-model="formData.isInternationalOperate"
                    :disabled="
                      fieldDisabled.indexOf('是否国际化经营') == -1
                        ? false
                        : true
                    "
                  >
                    <el-radio
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col
                :span="6"
                style="padding-left: 0px"
                v-show="formData.isInternationalOperate == '1'"
              >
                <el-form-item
                  label="国际化经营类型"
                  prop="internationalOperateType"
                  label-width="0"
                >
                  <template #label="{ label }">
                    <div class="hidden">{{ label }}</div>
                  </template>
                  <el-select
                    class="w-full"
                    :disabled="
                      fieldDisabled.indexOf('是否国际化经营') == -1
                        ? false
                        : true
                    "
                    v-model="formData.internationalOperateType"
                    placeholder="请选择国际化经营类型"
                  >
                    <el-option
                      v-for="item in international_operate_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注信息" prop="remark">
                  <el-input
                    :disabled="
                      fieldDisabled.indexOf('备注信息') == -1 ? false : true
                    "
                    v-model="formData.remark"
                    placeholder="填写备注信息"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </div>

    <!-- 物料选择弹窗 -->
    <ProductDialog
      v-model="dialogData.open"
      :dialogData="dialogData"
      @getData="productDialogFn"
    />

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    ></SelectDialog>

    <!-- 提交审批 -->
    <SubmissionProcess
      :dialog-param="examineParam"
      :flowOptions="flowOptions"
      @initiate="handleClose('initiate')"
      @close="handleClose('examine')"
    ></SubmissionProcess>

    <!-- 客户弹出框下拉框 -->
    <SelectCustomer
      v-if="dialogParamA.isDialog"
      :dialog-param="dialogParamA"
      @ok="selectCustomerData"
      @close="
        val => {
          dialogParamA.isDialog = false
        }
      "
    />

    <!-- 选择合同 -->
    <RelatedContract
      :relatedParams="params"
      @closeDialog="closeDialog"
      @relatedOver="relatedOver"
    />

    <!-- 选择项目 -->
    <RelatedProject
      :relatedParams="proParams"
      @closeDialog="closePro"
      @relatedOver="relatedPro"
    />
  </div>
</template>
<script setup name="PurchaseOrderForm">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useTagsViewStore from '@/store/modules/tagsView'
import {
  crudOption, // 子表公用配置
  order_business_type, //订单业务分类
  order_status, //订单状态
  yes_or_no, //是否
  pay_type, //付款方式
  settle_type, //结算方式
  invoice_manage_type, //订单发票类型
  measurement_unit, //产品单位
  order_property, //订单属性
  order_transport_type, //订单运输方式
  order_transport_man, //订单运费承担方
  order_pro_type, //订单产品类型
  order_bank_card, //订单收款账号
  international_operate_type, //国际化经营类型
  loadingSelect, //远程检索loading
  companyOption, //所属公司
  departmentOption, //部门树结构
  businessTypeOption, //业务类型树
  projectOptions, //项目数据
  queryProject, //检索项目
  contractOptions, //合同数据
  queryContract, //检索合同数据
  contactsOptions, // 联系人数据
  queryContacts, // 检索联系人数据
  queryWhsLimitEnt, // 检索仓库数据
  whsOptLimitEnt, //仓库数据
  querySupplier, // 检索供应商数据
  supplierOptions //供应商数据
} from '@/hooks/dict/order'
import { getInventory } from '@/api/warehouseManage/warehouse'
import { setPurchaseOrder, getPurchaseOrder } from '@/api/indentManage/indent'
import { getSupplierInfo } from '@/api/sourceModules/supplier'
import { delPayPlan } from '@/api/payManage/pay'
import { isMoneyNot, validateLen } from '@/utils/validate'
import { skipToError, getTreeNodeByParam, getPricipalId } from '@/utils/commo'
import useUserStore from '@/store/modules/user'
import useCommonStore from '@/store/modules/common'

import SubmissionProcess from '@/businessComponents/SubmissionProcess'
import {
  listProcess,
  getBusinessProStatus,
  getNodeData
} from '@/api/workflow/process'
const examineParam = ref({}) // 传递的参数
const isExamine = ref(true) // 判断是否走审批按钮
const flowOptions = ref([]) // 该业务的流程数据
const isCanStart = ref(true) // 判断该业务是否可以审批发起 以及办理详情 访问的时候不能审批 ===》针对编辑页面  办理详情

const commonStore = useCommonStore()

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const { proxy, type } = getCurrentInstance()
const { product_property } = proxy.useDict('product_property')
const props = defineProps({
  purchaseOrderId: {
    type: [Number, String],
    require: false
  },
  id: {
    type: [Number, String],
    require: false
  }
})
const data = reactive({
  formData: {
    deptId: userStore.userInfo.orgId,
    property: '0',
    proProperty: '2', //产品属性--,商品
    proType: '0', //产品类型--通用
    productInfoList: [],
    payPlanList: [],
    customerType: 'supplier', //客户类型 -- 供应商
    invoiceType: '3', //发票类型--增值税普通电子发票
    status: '1', //状态默认填单
    isInternationalOperate: '0' //是否国际化经营--否
  },
  formRules: {
    title: [
      {
        required: true,
        message: '请输入订单标题',
        trigger: 'blur'
      },
      validateLen(100)
    ],
    property: [
      {
        required: true,
        message: '请选择订单属性',
        trigger: 'change'
      }
    ],
    customerId: [
      {
        required: true,
        message: '请选择客户名称',
        trigger: 'change'
      }
    ],
    proProperty: [
      {
        required: true,
        message: '请选择产品属性',
        trigger: 'change'
      }
    ],
    proType: [
      {
        required: true,
        message: '请选择产品类型',
        trigger: 'change'
      }
    ],
    number: [
      {
        required: true,
        message: '请输入订单编号',
        trigger: 'blur'
      }
    ],
    businessType: [
      {
        required: true,
        message: '请选择所属业务分类',
        trigger: 'change'
      }
    ],
    deptId: [
      {
        required: true,
        message: '请选择所属公司',
        trigger: 'change'
      }
    ],
    transactionDept: [
      {
        required: false,
        message: '请选择业务部门',
        trigger: 'change'
      }
    ],
    _transactionId: [
      {
        required: false,
        message: '请选择业务员',
        trigger: 'change'
      }
    ],
    price: [
      {
        required: true,
        message: '请输入订单金额',
        trigger: 'blur'
      },
      {
        validator: isMoneyNot
      }
    ]
  },
  activeNames: ['基本信息', '采购明细', '付款计划', '其他信息'],
  crudOptionProduct: {
    ...crudOption, // 子表公用配置
    column: [
      {
        label: '产品名称',
        prop: 'name',
        cell: false,
        minWidth: '100',
        rules: [
          {
            required: true,
            message: '请输入产品名称',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '产品编号',
        prop: 'number',
        minWidth: '100',
        cell: false
      },
      {
        label: '仓库',
        prop: 'warehouse',
        cell: true,
        width: '150',
        rules: [
          {
            required: true,
            message: '请输入仓库',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '供应商',
        prop: 'customerId',
        cell: true,
        width: '150',
        rules: [
          {
            required: computed(
              () => fieldHidden.value.indexOf('采购单价') == -1
            ),
            message: '请选择供应商',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '供应商税号',
        prop: 'customerNumber',
        minWidth: '100',
        cell: true
      },
      {
        label: '规格型号',
        prop: 'specification',
        cell: false
      },
      {
        label: '单位',
        prop: 'unit',
        width: '60',
        type: 'select',
        dicData: measurement_unit,
        cell: false
      },
      {
        label: '库存量',
        prop: 'inventory',
        minWidth: '70',
        cell: false
      },
      {
        label: '采购数量',
        prop: 'num',
        type: 'number',
        min: 0,
        class: 'w-full',
        controls: false,
        precision: 0,
        minWidth: '100',
        rules: [
          {
            required: true,
            message: '请输入数量',
            trigger: 'blur'
          }
        ],
        blur: val => {
          const { value, row } = val
          // 算采购总价
          changeNum(value, row)
          // if (value && row.valorem) {
          //   row.totalPrice = (Number(value) * Number(row.valorem)).toFixed(2)
          // }
        },
        cell: true
      },
      {
        label: '采购单价',
        hide: computed(() =>
          fieldHidden.value.indexOf('采购单价') == -1 ? false : true
        ),
        prop: 'price',
        type: 'number',
        min: 0,
        class: 'w-full',
        controls: false,
        precision: 2,
        minWidth: '100',
        rules: [
          {
            required: true,
            message: '请输入采购单价',
            trigger: 'blur'
          },
          {
            validator: isMoneyNot
          }
        ],
        blur: val => {
          const { value, row } = val
          changePrice(value, row)
          changeValorem(row.valorem, row)
          // if (row.taxRate) {
          //   // 算税额
          //   row.taxPrice = Number(
          //     ((Number(value) * Number(row.taxRate)) / 100).toFixed(2)
          //   )
          // }
          // // 算税率
          // if (row.taxPrice && value != 0) {
          //   row.taxRate = (Number(row.taxPrice) / Number(value)) * 100
          // }
          // // 算价税合计
          // if (row.taxPrice && value) {
          //   row.valorem = Number(value) + Number(row.taxPrice)
          // } else {
          //   row.valorem = Number(value) + 0
          // }
          // row.totalPrice = (Number(value) * Number(row.num)).toFixed(2)
        },
        cell: true
      },
      {
        label: '税额',
        hide: computed(() =>
          fieldHidden.value.indexOf('税额') == -1 ? false : true
        ),
        prop: 'taxPrice',
        type: 'number',
        min: 0,
        class: 'w-full',
        controls: false,
        minWidth: '100',
        rules: [
          {
            required: false,
            message: '请输入税额',
            trigger: 'blur'
          },
          {
            validator: isMoneyNot
          }
        ],
        blur: val => {
          const { value, row } = val
          changeTaxPrice(value, row)
          changeValorem(row.valorem, row)
          // // 算税率
          // if (row.price && row.price != 0) {
          //   row.taxRate = (Number(value) / Number(row.price)) * 100
          // }
          // // 算价税合计
          // if (row.price && value >= 0) {
          //   row.valorem = Number(value) + Number(row.price)
          // }
        },
        cell: true
      },
      {
        label: '税率(%)',
        hide: computed(() =>
          fieldHidden.value.indexOf('税率') == -1 ? false : true
        ),
        prop: 'taxRate',
        type: 'number',
        // max: 100,
        class: 'w-full',
        controls: false,
        minWidth: '100',
        precision: 0,
        rules: [
          {
            required: false,
            message: '请输入税率(%)',
            trigger: 'blur'
          }
        ],
        blur: val => {
          const { value, row } = val
          changeTaxRate(value, row)
          changeTaxPrice(row.taxPrice, row)
          changeValorem(row.valorem, row)
          // // 算税额
          // if (row.price && row.price != 0) {
          //   row.taxPrice = Number(
          //     ((Number(value) * Number(row.price)) / 100).toFixed(2)
          //   )
          // }
        },
        cell: true
      },
      {
        label: '价税合计',
        hide: computed(() =>
          fieldHidden.value.indexOf('价税合计') == -1 ? false : true
        ),
        prop: 'valorem',
        type: 'number',
        min: 0,
        class: 'w-full',
        controls: false,
        precision: 2,
        minWidth: '100',
        rules: [
          {
            required: true,
            message: '请输入价税合计',
            trigger: 'blur'
          },
          {
            validator: isMoneyNot
          }
        ],
        blur: val => {
          const { value, row } = val
          // 算采购总价
          if (value && row.num) {
            row.totalPrice = (Number(value) * Number(row.num)).toFixed(2)
          }
        },
        cell: true
      },
      {
        label: '采购总价(元)',
        prop: 'totalPrice',
        minWidth: '100',
        hide: computed(() =>
          fieldHidden.value.indexOf('采购总价') == -1 ? false : true
        ),
        cell: false
      },
      {
        label: '赠品',
        hide: computed(() =>
          fieldHidden.value.indexOf('赠品') == -1 ? false : true
        ),
        prop: 'present',
        minWidth: '100',
        // type: 'textarea',
        // maxRows: 1,
        rules: [
          {
            required: false,
            message: '请输入赠品',
            trigger: 'blur'
          }
        ],
        cell: true
      },
      {
        label: '备注',
        hide: computed(() =>
          fieldHidden.value.indexOf('备注') == -1 ? false : true
        ),
        prop: 'remark',
        // type: 'textarea',
        // maxRows: 1,
        minWidth: '100',
        rules: [
          {
            required: false,
            message: '请输入备注',
            trigger: 'blur'
          }
        ],
        cell: true
      }
    ]
  },
  crudOptionRepayment: {
    ...crudOption, // 子表公用配置
    menuWidth: 80,
    column: [
      {
        label: '期次',
        prop: 'period',
        width: '60',
        rules: [
          {
            required: true,
            message: '期次',
            trigger: 'blur'
          }
        ],
        value: '1',
        cell: false
      },
      {
        label: '计划付款日期',
        prop: 'payPlanDate',
        type: 'date',
        cell: true,
        valueFormat: 'YYYY-MM-DD',
        rules: [
          {
            required: false,
            message: '请输入计划付款日期',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '计划付款占比(%)',
        prop: 'proportion',
        type: 'number',
        min: 0,
        max: 100,
        class: 'w-full',
        controls: false,
        precision: 0,
        rules: [
          {
            required: false,
            message: '请输入计划付款占比(%)',
            trigger: 'blur'
          }
        ],
        cell: true
      },
      {
        label: '计划付款金额(元)',
        prop: 'price',
        rules: [
          {
            required: false,
            message: '请输入计划付款金额(元)',
            trigger: 'blur'
          },
          {
            validator: isMoneyNot
          }
        ],
        cell: true
      },
      {
        label: '付款方式',
        prop: 'payType',
        type: 'select',
        dicData: pay_type,
        rules: [
          {
            required: false,
            message: '请选择付款方式',
            trigger: 'change'
          }
        ],
        cell: true
      },
      {
        label: '结算方式',
        prop: 'settleType',
        type: 'select',
        dicData: settle_type,
        rules: [
          {
            required: false,
            message: '请选择付款方式',
            trigger: 'change'
          }
        ],
        cell: true
      },
      {
        label: '付款账号',
        prop: 'bankCard',
        cell: true
      },
      {
        label: '备注',
        prop: 'remark',
        rules: [
          {
            required: false,
            message: '请输入备注',
            trigger: 'blur'
          }
        ],
        cell: true
      }
    ]
  },
  countCrudData: {},
  repaymentStatisticsData: {},
  dialogData: {
    open: false
  },
  showTrainingIndustry: '',
  userOption: {}, //人员选择下拉
  customerOption: {}, //客户选择下拉
  dialogParam: {},
  dialogParamA: {},
  fieldDisabled: [], //禁用字段
  fieldHidden: [
    '付款计划',
    '订单金额',
    '采购单价',
    '税额',
    '税率',
    '价税合计',
    '采购总价',
    '赠品',
    '备注'
  ], //隐藏字段
  formDisabled: false, // 禁用表单
  bpmnStatus: '' //表单标题
})
let {
  formData,
  formRules,
  activeNames,
  crudOptionProduct,
  crudOptionRepayment,
  countCrudData,
  repaymentStatisticsData,
  dialogData,
  showTrainingIndustry,
  userOption,
  customerOption,
  dialogParam,
  dialogParamA,
  fieldDisabled,
  fieldHidden,
  formDisabled,
  bpmnStatus
} = toRefs(data)

watchEffect(
  () => {
    if (product_property.value.length > 0) {
      product_property.value = product_property.value.filter(
        e => e.value !== '3'
      )
      console.log('product_property.value', product_property.value)
    }
  },
  { flush: 'post' }
)
onMounted(() => {
  // 判断所属业务分类
  showTrainingIndustry.value = computed(() => {
    // console.log('order_business_type=>2', order_business_type.value)
    let value = false
    let business = order_business_type.value.filter(e => {
      return formData.value.businessType == e.value
    })
    try {
      value = business[0].parentId == '1' || business[0].value == '1'
    } catch (error) {}
    return value
  })

  // 计算产品数据
  countCrudData.value = computed(() => {
    let obj = {
      num: 0,
      total: 0,
      totalDiscountPrice: 0,
      taxRate: 0,
      totalPrice: 0
    }
    if (
      formData.value.productInfoList &&
      formData.value.productInfoList.length > 0
    ) {
      formData.value.productInfoList.forEach(item => {
        obj.total = Number(item.num) + Number(obj.total)
        obj.totalDiscountPrice =
          Number(item.price) * Number(item.num) + Number(obj.totalDiscountPrice)
        obj.totalPrice = (
          Number(item.totalPrice) + Number(obj.totalPrice)
        ).toFixed(2)
        obj.taxRate = (
          (1 - Number(obj.totalPrice) / Number(obj.totalDiscountPrice)) *
          100
        ).toFixed(2)
        //         产品总数：countCrudData.total
        //产品总金额：countCrudData.totalDiscountPrice
        //         整单折扣：countCrudData.discount
        //         产品总金额： countCrudData.totalPrice
      })
      obj.num = formData.value.productInfoList.length
    }
    return obj
  })

  // 计算付款数据
  repaymentStatisticsData.value = computed(() => {
    let obj = {
      num: 0,
      proportion: 0,
      totalPrice: 0
    }
    if (formData.value.payPlanList && formData.value.payPlanList.length > 0) {
      formData.value.payPlanList.forEach(item => {
        obj.proportion = Number(item.proportion) + Number(obj.proportion)
        obj.totalPrice = Number(item.price) + Number(obj.totalPrice)
        //         付款占比.proportion
        //         付款金额 totalPrice
      })
      obj.num = formData.value.payPlanList.length
    }
    return obj
  })
})
// onUpdated(() => {
//   if (!formData.value.deptId) {
//     formData.value.deptId = userStore.userInfo.deptId
//     console.log('userStore==>', userStore.userInfo)
//     console.log('formData.value.deptId==>', formData.value.deptId)
//   }
// })
// watch(
//   () => formData.value.customerId,
//   (val, old) => {
//     changeCustomer(formData.value.customerId)
//   },
//   { deep: true }
// )
watch(
  [
    () => route.query.purchaseOrderId,
    () => props.purchaseOrderId,
    () => props.id
  ],
  async () => {
    if (route.query.purchaseOrderId && route.name == type.name) {
      await getFormData(route.query.purchaseOrderId)
    } else if (props.purchaseOrderId && route.name == 'EditPurchaseOrder') {
      await getFormData(props.purchaseOrderId)
      //根据业务查询审批状态
      await getBusinessProStatusFn()
      // 判断表单是否可编辑  获取当前流程节点
      let res = await getNodeData(props.purchaseOrderId)
      bpmnStatus.value = res.data?.nowTaskName
      formDisabled.value =
        res.data == null || res.data?.isFirst == 'Y' ? false : true
      fieldHidden.value =
        res.data == null || res.data?.isFirst == 'Y' ? fieldHidden.value : []
    } else if (props.id && route.name == 'WorkDetail') {
      await getFormData(props.id)
      // 获取流程节点数据
      if (route.query.processed) {
        // fieldDisabled.value
        let res = await getNodeData(props.id)
        console.log(getNodeData, 'getNodeData---')
        if (res.code !== 200) return
        bpmnStatus.value = res.data?.nowTaskName
        try {
          formDisabled.value = res.data?.formDisabled
        } catch (error) {}
        try {
          let resDis = res.data?.fieldDisabled
          fieldDisabled.value = resDis
            ? resDis.replaceAll(',', '，').split('，')
            : []
        } catch (error) {}
        try {
          let resHid = res.data?.fieldHidden
          fieldHidden.value = resHid
            ? resHid.replaceAll(',', '，').split('，')
            : []
        } catch (error) {}
      }
      formDisabled.value =
        !formDisabled.value && route.query.processed == 'true' ? false : true
      isCanStart.value = false
    } else if (route.name == type.name) {
      isExamine.value = true
      // 走业务流程
      initFlowFn('13')
    }
  },
  {
    immediate: true
  }
)

// 获取表单信息
async function getFormData(id) {
  proxy.$modal.loading('加载中')
  let res = await getPurchaseOrder(id)
  if (res.code !== 200) return
  let resData = {}
  resData = res.data
  // 客户数据
  resData.customerId
    ? (customerOption.value['customerId'] = [
        {
          label: resData.customerName, //? resData.customerName: resData.customerId,
          id: resData.customerId //? resData.customerId : resData.customerName
        }
      ])
    : ''
  //项目数据
  resData.projectId
    ? (projectOptions.value = [
        {
          proName: resData.projectName,
          projectId: resData.projectId
        }
      ])
    : ''
  //合同数据
  if (resData.contractId) {
    contractOptions.value = [
      {
        rcId: resData.contractId,
        contractName: resData.contractName
      }
    ]
  }
  // 仓库数据/产品行可编辑
  if (resData.productInfoList.length > 0) {
    resData.productInfoList.forEach((e, i) => {
      if (e.id) {
        resData.productInfoList[i].$cellEdit = true
        if (e.warehouse) {
          let contain = []
          contain = whsOptLimitEnt.value.filter(whs => whs.id == e.warehouse)
          contain.length == 0
            ? whsOptLimitEnt.value.push({
                id: e.warehouse,
                name: e.warehouseName
              })
            : ''
        }
        if (e.customerId) {
          let contain = []
          contain = supplierOptions.value.filter(
            supplier => supplier.id == e.customerId
          )
          contain.length == 0
            ? supplierOptions.value.push({
                id: e.customerId,
                supplierName: e.customerName
              })
            : ''
        }
      }
    })
  }
  if (resData.payPlanList.length > 0) {
    resData.payPlanList.forEach((e, i) => {
      if (e.id) {
        resData.payPlanList[i].$cellEdit = true
      }
    })
  }
  formData.value = resData

  // 获取业务员
  // if (formData.value.transactionId) {
  //   await getDefaultUserInfo(
  //     formData.value.transactionId,
  //     '_transactionId',
  //     'transactionId'
  //   )
  // }

  proxy.$modal.closeLoading()
}
// 付款计划有填都必填
function validatePayment() {
  if (formData.value.payPlanList.length) {
    const name = formData.value.payPlanList.filter(item => {
      if (
        (!item.payPlanDate ||
          !item.proportion ||
          !item.price ||
          !item.payType ||
          !item.settleType ||
          !item.bankCard) &&
        (item.payPlanDate ||
          item.proportion ||
          item.price ||
          item.payType ||
          item.settleType ||
          item.bankCard)
      ) {
        return item
      }
    })
    if (name.length) {
      return { result: !name.length, msg: '请输入付款方式和相关内容' }
    }
  }
  return { result: true }
}
// 保存/发起流程
async function handleSubmit(type) {
  // if (formData.value._transactionId) {
  //   formData.value.transactionId = getPricipalId(
  //     userOption.value['transactionId'],
  //     formData.value._transactionId
  //   ).toString()
  // }
  return new Promise((resolve, reject) => {
    proxy.$refs.form.validate(async (valid, msg) => {
      await proxy.$refs.crudProduct.validateCellForm().then(async err => {
        if (valid && !err) {
          // 付款计划有填都必填
          const response = validatePayment()
          if (!response.result) {
            proxy.$modal.msgWarning(response.msg)
            return false
          }
          let res = await setPurchaseOrder(formData.value)
          if (res.code !== 200) {
            reject(res)
            return
          }
          resolve(res)
          // type
          //   ? ''
          //   : proxy.$modal.msgSuccess(
          //       formData.value.id ? '修改成功' : '新增成功'
          //     )
          // if (!formData.value.id) {
          //   useTagsViewStore().delView(router.currentRoute.value)
          //   router.go(-1)
          // }
          await getFormData(res.data.id)
          // 审批流程id赋值
          examineParam.value.businessId = res.data.id
          if (type == 'examine') {
            handleExamine()
          } else if (type == 'save') {
            proxy.useReturn(
              '',
              () => {
                //返回上一步
                handleReturn()
              },
              async () => {
                //继续
              }
            )
          }
        } else {
          skipToError()
        }
      })
    })
  })
}
// 流程同意调用的方法
async function handleSave() {
  return await handleSubmit()
}
function handleReset() {
  proxy.resetForm('form')
}

/***************************业务流程 模块 start****************************************************************/
/*****审批模块  start*** */
/**
 * 提交审批 按钮
 发布需要的参数 examineParam 参数说明
  visible弹出框是否显示
  businessId //业务id
  businessName//业务名称（如：项目模块 businessName：项目名称）
  amount// 流程设计里面设计的条件参数值
  categoryCode //==>流程分类 页面查看 分类编码：项目1，订单2 客户3 	投标4 采购13
/**
 * 提交审批 按钮
 */
async function handleExamine() {
  if (!examineParam.value.businessId) {
    proxy.$modal.msgWarning('请重新发起审批')
    return false
  }
  examineParam.value.businessName = formData.value.title //订单标题
  examineParam.value.categoryCode = '13' //分类编码：项目1，订单2 客户3 	投标4
  examineParam.value.visible = true
}
// 关闭
const handleClose = type => {
  switch (type) {
    case 'examine':
      //弹出框关闭
      examineParam.value.visible = false
      break
    case 'initiate':
      //审批 发起成功
      isCanStart.value = false
      examineParam.value.visible = false
      handleReturn()
      break
  }
}
/*****审批模块  end*** */
/**
 * 业务流程整体思路：
 * 1.查询该业务是否有流程
 * 2.根据该业务流程来判断
 * * 2.1没有流程-提示不能新建数据
 * 3.点击发起申请【调组件】
 * * 只有一条流程时，下一环节人的显示 -再发起
 * * 多条流程时，选择流程，再选下一环节人的显示 -再发起
 * @param {*} type  业务类型 项目是1 订单业务2 	客户模块业务3 采购13
 */

async function initFlowFn(type) {
  // 1.查询该业务是否有流程
  let comRes = await listProcess({
    pageNum: 1,
    pageSize: 9999,
    category: type
  })
  flowOptions.value = comRes.rows || []
  // 2.根据
  if (JSON.stringify(flowOptions.value) == '[]') {
    //2.1 没有流程-提示不能新建数据
    if (route.name == type.name) {
      // 新建页面
      proxy.$modal.msgError('该业务没有配置流程，请先创建流程')
    } else {
      //编辑页面
      isExamine.value = false
    }
  } else {
    isExamine.value = true
  }
}
// 编辑页面的时候 -》根据业务查询审批状态
async function getBusinessProStatusFn() {
  let statusRes = await getBusinessProStatus({ businessId: formData.value.id })
  if (statusRes.data.canStart) {
    // canStart false时 不能发起，true则可以发起
    isCanStart.value = true
    initFlowFn('13')
  } else {
    isCanStart.value = false
  }
}
/***************************业务流程 模块 end****************************************************************/

// 选择客户时的方法
function changeCustomer(val) {
  getSupplierInfo(val).then(async res => {
    console.log('客户详情==》', res.data)
    let resData = res.data
    // 联系人赋值
    if (resData.contactList) {
      contactsOptions.value = resData.contactList
    }
    // 供应商编码赋值
    if (resData.bo.supplierTaxcode) {
      formData.value.customerNumber = resData.bo.supplierTaxcode
    }
    // 业务员赋值
    if (!formData.value._transactionId && resData.bo.userId) {
      await getDefaultUserInfo(
        resData.bo.userId,
        '_transactionId',
        'transactionId'
      )
      // formData.value._handleId = resData.bizCustomerAddDto.userId
    }
    // 业务部门赋值
    if (!formData.value.transactionDept && resData.bo.orgId) {
      formData.value.transactionDept = resData.bo.orgId
    }
  })
}
// 选择联系人时的方法
function changeLinkName(val) {
  let cusLink = contactsOptions.value.filter(item => {
    return item.id == val
  })
  formData.value.cusLinkName = cusLink[0].contactName
  console.log('cusLink==>', cusLink[0])
}

// 选择合同时的方法
function changeContract(val) {
  let contract = contractOptions.value.filter(item => {
    return item.rcId == val
  })
  formData.value.contractName = contract[0].contractName
  formData.value.contractNumber = contract[0].contractNum
}
// 选择项目时的方法
function changeProject(val) {
  let pro = projectOptions.value.filter(item => {
    return item.projectId == val
  })
  formData.value.projectName = pro[0].proName
  formData.value.projectNumber = pro[0].proNum
}

/**
 * 人员选择
 * @param keyName handleId:经办人  transactionId:业务员
 */
function selectUserFn(keyName) {
  switch (keyName) {
    case 'transactionId':
      dialogParam.value.type = keyName
      dialogParam.value.title = '请选择业务员'
      dialogParam.value.isDialog = true
      dialogParam.value.multiple = false
      dialogParam.value.nodeKey = 'uuid'
      dialogParam.value.defaultCheckedKeys = [formData.value['_' + keyName]]
      dialogParam.value.dataType = 'person'
      break
  }
}

// 人员选择确定
const selectDialogData = val => {
  switch (val.type) {
    case 'transactionId':
      userOption.value.transactionId = val.selectData
      formData.value.transactionName = val.labelData.toString()
      formData.value._transactionId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      break
    /* case 'transactionId':
      userOption.value.transactionId = val.selectData
      formData.value.transactionId = val.defaultCheckedKeys
      break */
  }
}

/**
 * 根据当前用户id转为uuid（id前加u）
 * @param val 输入用户的id
 * @param fieldName 需要赋值的字段
 * @param selectArr 用户的字典
 */
async function getDefaultUserInfo(val, fieldName, selectArr) {
  let userTree = await commonStore.getUseTreeData()
  userOption.value[selectArr] = []
  let id = ''
  if (val) {
    id = val
  }
  if (Array.isArray(id)) {
    formData.value[fieldName] = []
    id.forEach(item => {
      let obj = getTreeNodeByParam(userTree, item, 'id', [])
      userOption.value[selectArr].push(...obj)
      formData.value[fieldName].push(obj[0].uuid)
    })
  } else {
    //根据当前用户id获取uuid
    let obj = getTreeNodeByParam(userTree, id, 'id', [])
    userOption.value[selectArr] = obj
    formData.value[fieldName] = obj[0].uuid
  }
}
/**
 * 客户选择选择
 * @param keyName
 */
function selectCustomerFn(keyName, row) {
  dialogParamA.value.type = row.$index
  dialogParamA.value.tabVal = formData.value.customerType
  dialogParamA.value.tabShow = false
  dialogParamA.value.title = '供应商选择'
  dialogParamA.value.isDialog = true
  dialogParamA.value.multiple = false
  dialogParamA.value.nodeKey = 'id'
  dialogParamA.value.defaultCheckedKeys = row[keyName]
  dialogParamA.value.defaultCheckedLabel = row['customerName']
}

// 客户选择选择确定
const selectCustomerData = val => {
  // console.log('val==>', val)
  formData.value.customerType = val.tabVal
  if (
    formData.value.productInfoList[val.type].customerId !==
    val.defaultCheckedKeys.toString()
  ) {
    supplierOptions.value = val.selectData
    // 供应商名称赋值
    formData.value.productInfoList[val.type].customerName =
      val.labelData.toString()
    // 供应商税号赋值
    if (val.selectData.length > 0) {
      formData.value.productInfoList[val.type].customerNumber =
        val.selectData[0].supplierTaxcode
    } else {
      formData.value.productInfoList[val.type].customerNumber = ''
    }
    // 供应商id赋值
    formData.value.productInfoList[val.type].customerId = val.defaultCheckedKeys
      ? val.defaultCheckedKeys.toString()
      : null
  }
}
// 添加产品
function addProduct() {
  console.log('dialogData.value.open', dialogData.value.open)
  dialogData.value = {
    open: true,
    options: {
      tabsShow: false
    }
    // productQuery: {
    //   createUnit: formData.value.deptId, //产品所属单位
    //   zeroExitControl: '1', //0库存出库
    //   businessType: [] //所属板块
    // }
  }
}
// 确定添加产品
function productDialogFn(val, tabName) {
  switch (tabName) {
    case 'ProductMange':
      val.forEach(e => {
        formData.value.productInfoList.push({
          ...e,
          ...{
            $cellEdit: true,
            num: 1,
            price: e.price,
            productId: e.id,
            totalPrice: e.price
          }
        })
      })
      break
  }
  queryWhsLimitEnt('', { unit: formData.value.deptId })
}
// 改变产品数量时
function changeNum(value, row) {
  // 算采购总价
  if (value && row.valorem) {
    row.totalPrice = (Number(value) * Number(row.valorem)).toFixed(2)
  }
}
// 改变产品采购单价时
function changePrice(value, row) {
  if (row.taxRate) {
    // 算税额
    row.taxPrice = Number(
      ((Number(value) * Number(row.taxRate)) / 100).toFixed(2)
    )
  }
  // 算税率
  if (row.taxPrice && value != 0) {
    row.taxRate = (Number(row.taxPrice) / Number(value)) * 100
  }
  // 算价税合计
  if (row.taxPrice && value) {
    row.valorem = Number(value) + Number(row.taxPrice)
  } else {
    row.valorem = Number(value) + 0
  }
}
// 改变产品税额时
function changeTaxPrice(value, row) {
  // 算税率
  if (row.price && row.price != 0) {
    row.taxRate = (Number(value) / Number(row.price)) * 100
  }
  // 算价税合计
  if (row.price && value >= 0) {
    row.valorem = Number(value) + Number(row.price)
  }
}
// 改变产品税率时
function changeTaxRate(value, row) {
  // 算税额
  if (row.price && row.price != 0) {
    row.taxPrice = Number(
      ((Number(value) * Number(row.price)) / 100).toFixed(2)
    )
  }
  // row.totalPrice = (Number(value) * Number(row.num)).toFixed(2)
}
// 改变产品价税合计时
function changeValorem(value, row) {
  // 算采购总价
  if (value && row.num) {
    row.totalPrice = (Number(value) * Number(row.num)).toFixed(2)
  }
}
// changeWhs选择仓库时
async function changeWhs(val, row) {
  let params = {
    productId: row.productId,
    warehouseId: val
  }
  let res = await getInventory(params)
  row.inventory = res.data
}
// 选择供应商时
async function changeSupplier(val, row) {
  getSupplierInfo(val).then(async res => {
    console.log('客户详情==》', res.data)
    let resData = res.data
    // 供应商编码赋值
    if (resData.bo.supplierTaxcode) {
      row.customerNumber = resData.bo.supplierTaxcode
    }
    // 供应商名称
    if (resData.bo.supplierName) {
      row.customerName = resData.bo.supplierName
    }
  })
}
// 删除产品行
function delRowProduct(row, index, done) {
  proxy
    .$confirm('是否删除该产品', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      formData.value.productInfoList.splice(index, 1)
      proxy.$message({
        type: 'success',
        message: '删除成功!'
      })
    })
    .catch(() => {})
}

// 添加付款
function addRowRepayment() {
  formData.value.payPlanList.push({ $cellEdit: true }) //, price: 0
  console.log('product==>', formData.value.payPlanList)
}
// 付款计划期次赋值
function rowIndex(row) {
  row.period = row.$index + 1
  return row.$index + 1
}
// 删除付款行
function delRowRepayment(row, index, done) {
  proxy
    .$confirm('是否删除该付款计划', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      if (row.id) {
        delPayPlan(row.id).then(e => {
          formData.value.payPlanList.splice(index, 1)
          proxy.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      } else {
        formData.value.payPlanList.splice(index, 1)
        proxy.$message({
          type: 'success',
          message: '删除成功!'
        })
      }
    })
    .catch(() => {})
}

/****    关联合同开始++++++++++++++++++++++++++++    ***/

const params = ref({
  visible: false,
  businessId: '',
  businessName: '客户名称'
})
// 打开弹窗
function activeDialog() {
  // const id = formData.value.customerId
  // if (!id) {
  //   proxy.$modal.msgError('请先选择客户名称')
  // }
  const ids = formData.value.contractId
  params.value = {
    visible: true, // 显示dialog
    businessId: '', //id, // 根据id查询合同列表
    businessName: '', //customerOption.value['customerId'][0].label, // 名称 -- 显示dialog title
    multiple: false, // 是否多选
    defaultSelect: ids ? ids : [] // 默认选择数据
  }
}

// 弹窗确认完成回调
function relatedOver(val) {
  console.log('nnn', val)
  const ids = params.value.multiple
    ? val.map(v => v.rcId).toString() || ''
    : val.rcId
  const names = params.value.multiple
    ? val.map(v => v.contractName).toString() || ''
    : val.contractName
  const nums = params.value.multiple
    ? val.map(v => v.contractNum).toString() || ''
    : val.contractNum
  formData.value.contractId = ids
  formData.value.contractName = names
  formData.value.contractNumber = nums
  closeDialog()
}

// 关闭弹窗
function closeDialog() {
  params.value.visible = false
}

// el-input clear函数
function clearAll() {
  formData.value.contractId = ''
  formData.value.contractName = ''
  formData.value.contractIds = []
  formData.value.contractNames = []
  formData.value.contractNumber = ''
}
/****    ++++++++++++++++++++++++++++    ***/

/****    关联项目  开始  ***/
const proParams = ref({
  visible: false,
  businessId: '',
  businessName: '客户名称'
})
// 打开弹窗
function selectPro() {
  // const id = formData.value.customerId
  // if (!id) {
  //   proxy.$modal.msgError('请先选择客户名称')
  //   return false
  // }
  const ids = formData.value.projectId
  proParams.value = {
    visible: true, // 显示dialog
    businessId: '', //id, //客户id
    businessName: '', //formData.value.customerName, //客户名称
    multiple: false, // 是否多选
    defaultSelect: ids ? ids : [] // 默认选择数据
  }
  // 注意： 如果不需要选客户名称的话，这个businessId，businessName 可以不传
}

// 弹窗确认完成回调
function relatedPro(val) {
  if (val) {
    console.log(val, 'val')
    const name = proParams.value.multiple
      ? val.map(v => v.proName).toString() || ''
      : val.proName

    const ids = proParams.value.multiple
      ? val.map(v => v.projectId) || []
      : val.projectId

    const nums = proParams.value.multiple
      ? val.map(v => v.proNum) || []
      : val.proNum

    formData.value.projectId = ids
    formData.value.projectName = proParams.value.multiple
      ? val.map(v => v.proName)
      : name
    formData.value.projectNumber = nums
  }
  closePro()
}

// 关闭弹窗
function closePro() {
  proParams.value.visible = false
}

// el-input clear函数
function clearPro() {
  formData.value.projectId = null
  formData.value.projectName = null
}
/****    关联项目  end   ***/

// 返回、关闭页面
function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}

//暴露出保存方法
defineExpose({ handleSave })
</script>
<style scoped>
.form-box :deep(.w-full) {
  width: 100%;
}
/* .order-form :deep(.avue-crud__menu) {
  border-bottom: 1px solid #eee;
} */
.form-box:deep(.form-title:before) {
  content: '▋';
  display: inline-block;
  color: #409eff;
}

:deep(.avue-crud__empty) {
  padding: 0;
}
</style>
